<?php


namespace apps\marriage\core\service;


use apps\marriage\core\model\MemberVisit;
use apps\marriage\core\model\SystemNotice;
use apps\marriage\core\model\UserPlatform;
use apps\marriage\core\model\UserSystemNotice;
use think\facade\Log;
use vm\com\BaseModel;
use vm\com\BaseService;
use vm\org\queue\QueueFactory;

class MemberVisitService extends BaseService
{

    /**
     * @return MemberVisit
     */
    protected function getModel()
    {
        return new MemberVisit();
    }

    /**
     * @return UserService
     */
    protected function getUserService()
    {
        return service('User', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|SiteConfigService
     */
    protected function getSiteConfigService()
    {
        return service('SiteConfig', SERVICE_NAMESPACE);
    }

    /**
     * @return MemberProfileService
     */
    protected function getMemberProfileService()
    {
        return service('MemberProfile', SERVICE_NAMESPACE);
    }

    /**
     * @return SystemNoticeService
     */
    protected function getSystemNoticeService()
    {
        return service('SystemNotice', SERVICE_NAMESPACE);
    }

    /**
     * @return UserSystemNoticeService
     */
    protected function getUserSystemNoticeService()
    {
        return service('UserSystemNotice', SERVICE_NAMESPACE);
    }

    /**
     * @return UserPlatformService
     */
    protected function getUserPlatformService()
    {
        return service('UserPlatform', SERVICE_NAMESPACE);
    }

    public function save($userId, $memberProfileId)
    {
        $this->insert([
            'user_id' => $userId,
            'member_profile_id' => $memberProfileId,
            'add_time' => time()
        ], true);
        // 给被浏览人发送通知
        $visitor = $this->getUserService()->getByPk($userId);
        $visitorMemberProfile = $this->getMemberProfileService()->getByUserId($userId);
        $memberProfile = $this->getMemberProfileService()->getByPk($memberProfileId);
        $member = $this->getUserService()->getByPk($memberProfile['user_id']);
        $systemNoticeId = $this->getSystemNoticeService()->create([
            'title' => '用户来访提醒',
            'content' => $visitor['nick'] . '浏览了您的主页',
            'type' => SystemNotice::TYPE_SINGLE,
            'status' => SystemNotice::STATUS_PULLED,
            'recipient_id' => $member['id'],
            'manager_id' => 0,
            'url' => json_encode([
                'weapp' => '/pages/member/profile?id=' . $visitorMemberProfile['id'],
                'web' => '/member_profile?id=' . $visitorMemberProfile['id'],
                'app' => '/member/profile?id=' . $visitorMemberProfile['id']
            ])
        ]);
        $this->getUserSystemNoticeService()->create([
            'system_notice_id' => $systemNoticeId,
            'recipient_id' => $member['id'],
            'status' => UserSystemNotice::STATUS_WAIT_READ,
            'pull_time' => time()
        ]);

        // 给被浏览人发送公众号通知
        try {
            if($this->getUserPlatformService()->checkUserSubscribedMpAccount($member['id'])) {
                $userPlatform = $this->getUserPlatformService()->info([
                    'user_id' => $member['id'],
                    'platform' => UserPlatform::PLATFORM_WX_MP
                ]);
                if($userPlatform) {
                    $openid = $userPlatform['open_id'];
                    $wechatConfig = config('wechat');
                    $msgTemplateId = $wechatConfig['mp_msg_templates']['new_visitor_notice'];
                    $msgData = [
                        'first' => [
                            'value' => '有新用户来访',
                        ],
                        'keyword1' => [
                            'value' => $visitor['nick']
                        ],
                        'keyword2' => [
                            'value' => 'N/A'
                        ],
                        'keyword3' => [
                            'value' => date('Y-m-d H:i:s')
                        ],
                        'remark' => [
                            'value' => '[' . $visitor['nick'] . ']正在浏览你的个人资料，赶快看看TA的资料，缘分就在一瞬间。'
                        ]
                    ];
                    $url = $this->getSiteConfigService()->getValueByCode('mp_site') . '/member_profile?id=' . $visitorMemberProfile['id'];
                    $miniprogram = null;

                    $queueConfig = config('queue');
                    $queueHandler = QueueFactory::instance();
                    $queueHandler->set($queueConfig['queues']['mp_msg'], [
                        'openid' => $openid,
                        'template_id' => $msgTemplateId,
                        'data' => $msgData,
                        'url' => $url,
                        'miniprogram' => $miniprogram
                    ]);
                }
            }
        } catch (\Exception $e) {
            $log = 'FILE:' . $e->getFile() . "\r\n" . 'LINE:' . $e->getLine(). "\r\n" . 'MSG:' . $e->getMessage();
            Log::error($log);
        }
    }
}